from common.models import Region, Site
from django.db.models import Model
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from .models import Book, BookAuthor, Author, BookSource, BookDownloadUrl, AuthorType, Tag
from common.dao import get_site, get_default_region
from common.util import try_set_attrs

def save_books(site, books):
    site = get_site(site[0], site[1])
    for book in books:
        save_book(site, book)


def update_book_cover(book, cover_url):
    book.cover_url = cover_url
    book.save(update_fields=['cover_url'])
    #book.update(cover_url = cover_url)



def normalize_book_vm(book_vm):
    try_set_attrs(book_vm, {
        'isbn':' ',
        'year':2018,
        'language':'zh',
        'sub_title':'',
        'summary':'',        
        'authors':None,
        'page_cnt':0,
        'tags':None
    })

def save_book(site, book_vm):
    normalize_book_vm(book_vm)

    try:
        book_source = BookSource.objects.get(site=site, url=book_vm.source_url)
    except ObjectDoesNotExist:
        book_source = None
    if not book_source:
    # if book_vm.isbn:
    #     try:
    #         book = Book.objects.get(isbn=book_vm.isbn)
    #     except ObjectDoesNotExist:
    #         book = None
    # else:
    #     try:
    #         book = Book.objects.get(title=book_vm.title)
    #     except ObjectDoesNotExist:
    #         book = None
    #if book is None:
        book = Book(title=book_vm.title, year=book_vm.year,
                    cover_url=book_vm.cover_url, isbn=book_vm.isbn)
    else:
        book = book_source.book
    book.isbn = book_vm.isbn
    book.cover_url=book_vm.cover_url  
    book.title = book_vm.title
    book.year = book_vm.year
    if book_vm.sub_title:
        book.sub_title = book_vm.sub_title
    else:
        book.sub_title = ''
    book.summary = book_vm.summary or ''
    book.save()

    sort_no = 0
    if hasattr(book_vm, 'authors') and book_vm.authors:
        for author_name in book_vm.authors:
            sort_no = sort_no + 1
            author = save_author(author_name)
            _save_book_author(book, author, sort_no)
    elif hasattr(book_vm, 'author') and book_vm.author:
        sort_no = sort_no + 1
        author = save_author(book_vm.author)
        _save_book_author(book, author, sort_no)        
    else:
        author = get_anonymous()
        _save_book_author(book, author, sort_no)

    if hasattr(book_vm, 'translators') and book_vm.translators:
        for translator_name in book_vm.translators:
            sort_no = sort_no + 1
            translator = save_author(translator_name)
            try:
                book_author = BookAuthor.objects.get(
                    author=translator, book=book)
            except ObjectDoesNotExist:
                book_author = BookAuthor(
                    author=translator, book=book, author_type=AuthorType.Translator, sort_order=sort_no)
                book_author.save()

    # try:
    #     book_source = BookSource.objects.get(site=site, url=book_vm.source_url)
    # except ObjectDoesNotExist:
    if not book_source:
        book_source = BookSource(book=book, url=book_vm.source_url, site=site,
                                 cover_url=book_vm.cover_url, language=book_vm.language, page_cnt=book_vm.page_cnt)
    if hasattr(book_vm, 'book_id'):
        book_source.key_int = book_vm.book_id
    if hasattr(book_vm, 'book_cid'):
        book_source.key_char = book_vm.book_cid
    book_source.save()

    if hasattr(book_vm, 'download_urls') and book_vm.download_urls:
        for book_download_url, file_format, file_size in book_vm.download_urls:
            try:
                book_download_url = BookDownloadUrl.objects.get(
                    download_url=book_download_url)
            except ObjectDoesNotExist:
                book_download_url = BookDownloadUrl(
                    download_url=book_download_url, file_format=file_format, file_size=file_size, book_source=book_source)
                book_download_url.save()

    if book_vm.tags:
        [book.tags.add(save_tag(tag_name)) for tag_name in book_vm.tags]
        book.save()
    return book


def _save_book_author(book, author, sort_no):
    try:
        book_author = BookAuthor.objects.get(author=author, book=book)
    except ObjectDoesNotExist:
        book_author = BookAuthor(
            author=author, book=book, author_type=AuthorType.Author, sort_order=sort_no)
        book_author.save()
    except MultipleObjectsReturned:
        pass


def save_author(author_name):
    try:
        author = Author.objects.filter(name=author_name).first()
    except ObjectDoesNotExist:
        pass
    if author is None:
        region = get_default_region()
        author = Author(name=author_name, country=region)
        author.save()   
    return author


def get_anonymous():
    return save_author('anonymous')


def save_tag(tag_name):
    try:
        tag = Tag.objects.get(name=tag_name)
    except ObjectDoesNotExist:
        tag = Tag(name=tag_name)
        tag.save()
    except MultipleObjectsReturned:
        tag = Tag.objects.filter(name=tag_name).first()

    return tag


def get_books(site_id, page_no, page_size=100):
    return [x.book for x in BookSource.objects.filter(site__id=site_id)
            .filter(book__cover_url__startswith='http')
            .order_by('-book__id')
            [(page_no - 1) * page_size:page_no * page_size]]
